package br.edu.ufcg.dsc.services;

import java.util.List;

import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import br.edu.ufcg.dsc.domain.User;

public class UserService extends BaseService {

	public static void persist(User u) {
		EntityTransaction tx = entity.getTransaction();

		tx.begin();
		try {
			if (find(u.getLogin()) != null)
				entity.merge(u);
			else
				entity.persist(u);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} 
	}

	public static User find(String login) {
		return entity.find(User.class, login);
	}

	@SuppressWarnings("unchecked")
	public static List<User> findByName(String name) {
		Query q = entity
				.createQuery(
						"SELECT u FROM br.edu.ufcg.dsc.domain.User u WHERE u.name LIKE :name")
				.setParameter("name", name);
		List<User> l = q.getResultList();
		return l;
	}
	
	@SuppressWarnings("unchecked")
	public static List<User> findByType(String type) {
		return (List<User>) entity.createQuery
		("SELECT u FROM br.edu.ufcg.dsc.domain.User u WHERE u.type = :type")
		.setParameter("type", type).getResultList();
	}
}
